package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.article.mapper.ApArticleConfigMapper;
import com.heima.article.mapper.ApArticleContentMapper;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.ApArticleService;
import com.heima.article.service.ArticleFreemarkerService;
import com.heima.common.constant.ArticleConstants;
import com.heima.common.constant.BehaviorConstants;
import com.heima.common.redis.CacheService;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.article.dtos.ArticleHomeDto;
import com.heima.model.article.dtos.ArticleInfoDto;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApArticleConfig;
import com.heima.model.article.pojos.ApArticleContent;
import com.heima.model.article.vos.ArticleBehaviorVO;
import com.heima.model.article.vos.HotArticleVo;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.mess.ArticleVisitStreamMess;
import com.heima.utils.thread.UserThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ApArticleServiceImpl extends ServiceImpl<ApArticleMapper, ApArticle> implements ApArticleService {

    @Autowired
    private ApArticleConfigMapper apArticleConfigMapper;
    @Autowired
    private ApArticleContentMapper apArticleContentMapper;
    @Autowired
    private ArticleFreemarkerService articleFreemarkerService;
    @Autowired
    private CacheService cacheService;

    /**
     * 加载文章列表
     * @param dto
     * @param type      1 加载更多   2 加载最新
     * @param firstPage true  是首页  flase 非首页
     * @return
     */
    @Override
    public ResponseResult load2(ArticleHomeDto dto, Short type, boolean firstPage) {
        if(firstPage){
            log.info("首页加载缓存文章");
            String jsonStr = cacheService.get(ArticleConstants.HOT_ARTICLE_FIRST_PAGE + dto.getTag());
            if(!StringUtils.isEmpty(jsonStr)){
                List<HotArticleVo> hotArticleVoList = JSON.parseArray(jsonStr, HotArticleVo.class);
                ResponseResult responseResult = ResponseResult.okResult(hotArticleVoList);
                return responseResult;
            }
        }
        return load(dto,type);
    }

    /**
     * 回显用户行为
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult loadArticleBehavior(ArticleInfoDto dto) {
        if(dto == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        Integer userId = UserThreadLocalUtil.getUser();
        if(userId == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        Long articleId = dto.getArticleId();
        Integer authorId = dto.getAuthorId();
        //查看是否点赞文章
        Object isLike = cacheService.hGet(BehaviorConstants.LIKE_BEHAVIOR + articleId, userId.toString());
        ArticleBehaviorVO behaviorVO = new ArticleBehaviorVO();
        if(isLike != null){
            behaviorVO.setIslike(true);
        }
        //是否关注作者
        Double score = cacheService.zScore(BehaviorConstants.APUSER_FOLLOW_RELATION + userId, authorId.toString());
        if(score != null){
            behaviorVO.setIsfollow(true);
        }
        //是否不喜欢该文章
        Object isUnLike = cacheService.hGet(BehaviorConstants.UN_LIKE_BEHAVIOR + articleId, userId.toString());
        if(isUnLike != null){
            behaviorVO.setIsunlike(true);
        }
        //是否收藏文章
        Object isCollection = cacheService.hGet(BehaviorConstants.COLLECTION_BEHAVIOR + articleId, userId.toString());

        if(isCollection != null){
            behaviorVO.setIscollection(true);
        }
        return ResponseResult.okResult(behaviorVO);
    }

    /**
     * 更新文章的分值  同时更新缓存中的热点文章数据
     * @param mess
     */
    @Override
    public void updateScore(ArticleVisitStreamMess mess) {
        log.info("【更新文章分值】---- begin");
        //1.更新文章的阅读、点赞、收藏、评论的数量
        ApArticle apArticle = updateArticle(mess);
        log.info("article:{}",apArticle);
        //2.计算文章的分值
        Integer score = computeScore(apArticle);
        score = score * 3;

        //3.替换当前文章对应频道的热点数据
        replaceDataToRedis(apArticle, score, ArticleConstants.HOT_ARTICLE_FIRST_PAGE + apArticle.getChannelId());

        //4.替换推荐对应的热点数据
        replaceDataToRedis(apArticle, score, ArticleConstants.HOT_ARTICLE_FIRST_PAGE + ArticleConstants.DEFAULT_TAG);
        log.info("【更新文章分值】---- end");
    }


    /**
     * 替换数据并且存入到redis
     * @param apArticle
     * @param score
     * @param s
     */
    private void replaceDataToRedis(ApArticle apArticle, Integer score, String s) {
        log.info("【替换数据】---- begin");
        String articleListStr = cacheService.get(s);
        if (!StringUtils.isEmpty(articleListStr)) {
            List<HotArticleVo> hotArticleVoList = JSON.parseArray(articleListStr, HotArticleVo.class);

            boolean flag = true;

            //如果缓存中存在该文章，只更新分值
            for (HotArticleVo hotArticleVo : hotArticleVoList) {
                if (hotArticleVo.getId().equals(apArticle.getId())) {
                    hotArticleVo.setScore(score);
                    flag = false;
                    break;
                }
            }

            //如果缓存中不存在，查询缓存中分值最小的一条数据，进行分值的比较，如果当前文章的分值大于缓存中的数据，就替换
            if (flag) {
                if (hotArticleVoList.size() >= 30) {
                    hotArticleVoList = hotArticleVoList.stream().sorted(Comparator.comparing(HotArticleVo::getScore).reversed()).collect(Collectors.toList());
                    HotArticleVo lastHot = hotArticleVoList.get(hotArticleVoList.size() - 1);
                    if (lastHot.getScore() < score) {
                        hotArticleVoList.remove(lastHot);
                        HotArticleVo hot = new HotArticleVo();
                        BeanUtils.copyProperties(apArticle, hot);
                        hot.setScore(score);
                        hotArticleVoList.add(hot);
                    }
                } else {
                    HotArticleVo hot = new HotArticleVo();
                    BeanUtils.copyProperties(apArticle, hot);
                    hot.setScore(score);
                    hotArticleVoList.add(hot);
                }
            }
            //缓存到redis
            hotArticleVoList = hotArticleVoList.stream().sorted(Comparator.comparing(HotArticleVo::getScore).reversed()).collect(Collectors.toList());
            cacheService.set(s, JSON.toJSONString(hotArticleVoList));
            log.info("【替换数据】---- end");

        }
    }

    /**
     * 计算文章的具体分值
     * @param apArticle
     * @return
     */
    private Integer computeScore(ApArticle apArticle) {
        Integer score = 0;
        if(apArticle.getLikes() != null){
            score += apArticle.getLikes() * ArticleConstants.HOT_ARTICLE_LIKE_WEIGHT;
        }
        if(apArticle.getViews() != null){
            score += apArticle.getViews();
        }
        if(apArticle.getComment() != null){
            score += apArticle.getComment() * ArticleConstants.HOT_ARTICLE_COMMENT_WEIGHT;
        }
        if(apArticle.getCollection() != null){
            score += apArticle.getCollection() * ArticleConstants.HOT_ARTICLE_COLLECTION_WEIGHT;
        }
        return score;
    }

    /**
     * 更新文章行为数量
     * @param mess
     */
    private ApArticle updateArticle(ArticleVisitStreamMess mess) {
        log.info("【更新文章行为数量】---- begin");
        ApArticle apArticle = getById(mess.getArticleId());
        apArticle.setCollection(apArticle.getCollection()==null?0:apArticle.getCollection()+mess.getCollect());
        apArticle.setComment(apArticle.getComment()==null?0:apArticle.getComment()+mess.getComment());
        apArticle.setLikes(apArticle.getLikes()==null?0:apArticle.getLikes()+mess.getLike());
        apArticle.setViews(apArticle.getViews()==null?0:apArticle.getViews()+mess.getView());
        updateById(apArticle);
        log.info("【更新文章行为数量】---- end");
        return apArticle;
    }

    /**
     * 保存app端相关文章
     *
     * @param dto
     * @return
     */
    @Override
    @Transactional
    public ResponseResult saveArticle(ArticleDto dto) {
        //1.检查参数
        log.info("【检查参数】dto:{}",dto);
        if(dto == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        ApArticle apArticle = new ApArticle();
        BeanUtils.copyProperties(dto, apArticle);
        ApArticleContent apArticleContent = new ApArticleContent();
        //2.判断是否存在id
        if(dto.getId() == null){
            log.info("【文章id不存在】");
            //2.1 不存在id  保存  文章  文章配置  文章内容
            log.info("【保存文章】ApArticle:{}",apArticle);
            save(apArticle);
            ApArticleConfig apArticleConfig = new ApArticleConfig(apArticle.getId());
            log.info("【保存文章配置】ApArticleConfig:{}",apArticleConfig);
            apArticleConfigMapper.insert(apArticleConfig);

            apArticleContent.setArticleId(apArticle.getId());
            apArticleContent.setContent(dto.getContent());
            log.info("【保存文章内容】apArticleContent:{}",apArticleContent);
            apArticleContentMapper.insert(apArticleContent);
        }else{
            //2.2 存在id   修改  文章  文章内容
            log.info("【修改文章】ApArticle:{}",apArticle);
            updateById(apArticle);

            apArticleContent = apArticleContentMapper.selectOne(Wrappers.<ApArticleContent>lambdaQuery().eq(ApArticleContent::getArticleId, dto.getId()));
            apArticleContent.setContent(dto.getContent());

            log.info("【修改文章内容】apArticleContent:{}",apArticleContent);
            apArticleContentMapper.updateById(apArticleContent);
        }
        //异步调用，生成静态文件上传到minio中
        articleFreemarkerService.buildArticleToMinIO(apArticle,apArticleContent.getContent());
        //3.结果返回  文章的id
        log.info("返回结果为文章id");
        return ResponseResult.okResult(apArticle.getId());
    }



    // 单页最大加载的数字
    private final static short MAX_PAGE_SIZE = 50;

    /**
     * 根据参数加载文章列表
     * @param dto
     * @param type 1 -加载更多 | 2加载最新
     * @return
     */
    public ResponseResult load(ArticleHomeDto dto,Short type) {
        log.info("【{}】类的【{}】方法开始执行",
                this.getClass().getName(),
                Thread.currentThread().getStackTrace()[1].getMethodName());
        //1.校验参数
        Integer size = dto.getSize();
        if(size == null || size == 0){
            size = 10;
        }
        size = Math.min(size,MAX_PAGE_SIZE);
        dto.setSize(size);
        log.info("【校验参数-size】--size:【{}】",size);

        //参数类型校验
        if(type != ArticleConstants.LOADTYPE_LOAD_MORE && type != ArticleConstants.LOADTYPE_LOAD_NEW){
            type = ArticleConstants.LOADTYPE_LOAD_MORE;
        }
        log.info("【校验参数-type】--type:【{}】",type);
        //频道校验
        if(StringUtils.isEmpty(dto.getTag())){
            dto.setTag(ArticleConstants.DEFAULT_TAG); //默认频道
        }
        log.info("【校验参数-tag】--tag:【{}】",dto.getTag());
        //时间校验
        if(dto.getMaxBehotTime() == null) dto.setMaxBehotTime(new Date());
        if(dto.getMinBehotTime() == null) dto.setMinBehotTime(new Date());
        log.info("【校验参数-time】--time:【getMaxBehotTime:{} | getMinBehotTime:{} 】",dto.getMaxBehotTime(),dto.getMinBehotTime());
        //2.查询数据
        log.info("开始查询数据");
        List<ApArticle> articleList = this.baseMapper.loadArticleList(dto, type);
        log.info("查询成功:【{}】",articleList);
        //3.结果封装
        return ResponseResult.okResult(articleList);

    }


}
